﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Snake {

    /// <summary>
    /// 蛇的身段
    /// </summary>
    internal class Segment {
        private Snake snake;
        private int index;
        private float minDistanceOfFront = 0;
        private Transform body;

        public Segment(Snake snake, Transform body, int index) {
            this.snake = snake;
            this.body = body;
            this.index = index;
        }

        public Transform getBody() {
            return body;
        }

        public void setMinDistanceOfFront(float min) {
            minDistanceOfFront = min;
            if (0 == index)
                return;
            TowardDistance();
        }

        public void TowardDistance() {
            if (0 == index)
                return;

            Vector3 preDirection = Previous().getDirection();
            Vector3 curDirection = getDirection();
            if (Vector3.Angle(preDirection, curDirection) > 90) {
                return;
            }

            Vector3 position2 = Previous().getBody().localPosition;
            if (Vector2.Distance(position2, getBody().localPosition) < minDistanceOfFront * getBody().localScale.x) {
                return;
            }
            Vector3 position1 = position2 - curDirection * minDistanceOfFront * getBody().localScale.x;
            position1.z = position2.z + 0.001f;
            getBody().localPosition = position1;
        }

        public void TowardFront() {
            if (0 == index)
                return;

            Transform pre = snake.getIndexBody(index - 1);
            getBody().right = Vector3.Lerp(pre.right, pre.right, Time.deltaTime * 20);
        }

        public Vector3 getDirection() {
            if (index == 0) {
                return snake.getIndexSegment(1).getDirection();
            }
            Vector3 p = snake.getIndexBody(index - 1).localPosition - getBody().localPosition;
            p.z = 0;
            return p.normalized;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public Segment Previous() {
            if (index == 0)
                return null;
            return snake.getIndexSegment(index - 1);
        }

        public float getMinDistanceOfFront() {
            return minDistanceOfFront;
        }
    }
}
